<template>
  <div id="root">
    <mu-appbar class="mu-appbar" :z-depth="2" color="primary" :title="appBarTitle"></mu-appbar>

    <div id="list-wrapper">
      <mu-load-more :loaded-all="loadedAll" :loading="loading" @load="load">
        <mu-list @change="onItemClick">
          <mu-list-item
                  button
                  :ripple="true"
                  :key="index"
                  :value="index"
                  v-for="(item, index) in listData">
            <mu-list-item-title :style="selectedIndex === index ? 'color: #ff4081' : ''">
              {{item}}
            </mu-list-item-title>
          </mu-list-item>
        </mu-list>
      </mu-load-more>
    </div>

    <mu-dialog title="确定信息" width="600" max-width="80%"
               :esc-press-close="false"
               :overlay-close="false"
               :open.sync="openDialog">
      <div>
        <div class="dialog-text-wrap">
          <h6 class="dialog-text-label">省市区（镇）</h6>
          <p class="dialog-text">{{dialog.address}}</p>
        </div>
        <div class="dialog-text-wrap">
          <h6 class="dialog-text-label">医院</h6>
          <p class="dialog-text">{{dialog.hospital}}</p>
        </div>
        <div class="dialog-text-wrap">
          <h6 class="dialog-text-label">科室</h6>
          <p class="dialog-text">{{dialog.department}}</p>
        </div>
        <div class="dialog-text-wrap" v-show="dialog.doctor.length !== 0">
          <h6 class="dialog-text-label">医生</h6>
          <p class="dialog-text">{{dialog.doctor}}</p>
        </div>
        <div class="dialog-text-wrap">
          <h6 class="dialog-text-label">时间</h6>
          <p class="dialog-text">{{dialog.date}}</p>
        </div>
      </div>
      <mu-button slot="actions" flat color="primary" @click="onDialogCancel">取消</mu-button>
      <mu-button slot="actions" flat color="primary" @click="onDialogConfirm">确定</mu-button>
    </mu-dialog>

    <mu-container class="nav-wrapper">
      <mu-flex class="nav" justify-content="center">
        <mu-button
                flat
                class="d-flex flex-fill"
                color="primary"
                :disabled="step === 0"
                @click="onBtnPreviousClick">{{btnPrevious}}
        </mu-button>
        <mu-button
                id="btn-next"
                class="d-flex flex-fill"
                color="primary"
                :disabled="step !== 5 && selectedIndex < 0"
                @click="onBtnNextClick">{{btnNext}}
        </mu-button>
      </mu-flex>
    </mu-container>
  </div>
</template>

<script lang="ts">
  import districts from '../../../phr/common/districts';
  import HospitalService from '../../service/hospital/HospitalService';
  import AppointmentService from '../../service/hospital/AppointmentService';
  import {SUCCESS} from '../../common/ErrorCode';

  let constant = {
    network_error: '网络异常',
    no_data: '没有数据',
    select_province: '选择省市',
    select_city: '选择市区',
    select_district: '选择区镇',
    select_hospital: '选择医院',
    select_department: '选择科室',
    select_doctor: '选择医生',
    select_date: '选择时间',
    previous_step: '上一步',
    next_step: '下一步',
    finish: '完成',
    confirm_message: '确定信息',
    nameSteps: {
      province: 0,
      city: 1,
      district: 2,
      hospital: 3,
      department: 4,
      doctor: 5,
      datetime: 6,
      lastStep: 6
    },
    districts: districts,
    provinces: districts[100000],
    departments: ['全科', '内科', '外科', '妇科', '儿科', '骨科', '皮肤科', '精神心理科'],
    doctors: ['扁鹊', '华佗', '李时珍', '张仲景', '孙思邈', '王叔和', '巢元方', '王冰', '王唯一', '唐慎微', '许叔微', '朱丹溪', '薛己', '张景岳', '张石顽', '薛雪', '王清任', '南丁格尔'],
  };

  export default {

    data() {
      return {
        appBarTitle: constant.select_province,
        btnPrevious: constant.previous_step,
        btnNext: constant.next_step,
        // 选择的列表项下标
        selectedIndex: -1,
        /*
         * 分别表示 provinces（省）的下标，
         * cities（市）的下标，
         * regions（区）的下标，
         * hospitals（医院）的下标，
         * departments（科室）的下标，
         * doctors（医生）的下标
         * dateList（时间）的下标
         */
        indexes: [-1, -1, -1, -1, -1, -1, -1],
        page: 1,
        listData: constant.provinces,
        cache: {
          hospitals: [],
          dates: []
        },
        step: 0,
        loading: false,
        loadedAll: true,
        dialogTitle: constant.confirm_message,
        openDialog: false,
        dialog: {
          address: '',
          hospital: '',
          department: '',
          doctor: '',
          date: '',
        }
      }
    },
    watch: {
      step(value) {
        this.btnNext = constant.next_step;

        switch (value) {
          case constant.nameSteps.province:
            // 列表填充省的数据
            this.listData = constant.provinces;
            // 重新设置动作栏标题
            this.appBarTitle = constant.select_province;
            break;
          case constant.nameSteps.city:
            // 列表填充市的数据
            this.listData = constant.districts[this.indexes[value - 1]];
            // 重新设置动作栏标题
            this.appBarTitle = constant.select_city;
            break;
          case constant.nameSteps.district:
            // 列表填充县的数据
            this.listData = constant.districts[this.indexes[value - 1]];
            // 重新设置动作栏标题
            this.appBarTitle = constant.select_district;
            break;
          case constant.nameSteps.hospital:
            // 初始化变量
            this.page = 0;
            this.loadedAll = false;

            HospitalService.searchHospital(
                constant.provinces[this.indexes[0]],
                constant.districts[this.indexes[0]][this.indexes[1]],
                constant.districts[this.indexes[1]][this.indexes[2]],
                this.page)
                .then(res => {
                  if (res.code === SUCCESS) {
                    let arr = [];
                    res.value.value.forEach(it => {
                      arr.push(it.name);
                    });
                    this.listData = arr;

                    // 将医院列表缓存起来
                    this.cache.hospitals = res.value.value;

                    if (res.value.value.length === 0) {
                      // 没有数据
                      this.$toast.info(constant.no_data);
                    }
                    if (res.value.currentPage >= res.value.maxPage) {
                      // 所有医院已全部加载
                      this.loadedAll = true;
                    }
                  } else {
                    this.$toast.info(res.message);
                  }
                })
                .catch(e => {
                  console.log(e);
                  this.$toast.info(constant.network_error);
                });
            // 重新设置动作栏标题
            this.appBarTitle = constant.select_hospital;
            break;
          case constant.nameSteps.department:
            this.loadedAll = true;
            // 列表设置科室的数据
            this.listData = constant.departments;
            // 重新设置动作栏标题
            this.appBarTitle = constant.select_department;
            break;
          case constant.nameSteps.doctor:
            // 列表设置医生的数据
            this.listData = constant.doctors;
            // 重新设置动作栏标题
            this.appBarTitle = constant.select_doctor;
            break;
          case constant.nameSteps.datetime:
            let curDate = new Date();
            // 保存日期对象，便于上传到服务器
            let dateList = [];
            // 保存每个日期的文字，用于列表显示
            let texts = [];

            // 可以挂一星期以内的号
            for (let i = 0; i < 7; i++) {
              let d = new Date(curDate.getTime() + i * 24 * 60 * 60 * 1000);
              let obj = {
                year: d.getFullYear(),
                month: d.getMonth(),
                date: d.getDate(),
                day: d.getDay(),
              };
              let obj2 = {
                year: d.getFullYear(),
                month: d.getMonth(),
                date: d.getDate(),
                day: d.getDay(),
              };
              let dayString = '天';
              switch (obj.day) {
                case 1: dayString = '一'; break;
                case 2: dayString = '二'; break;
                case 3: dayString = '三'; break;
                case 4: dayString = '四'; break;
                case 5: dayString = '五'; break;
                case 6: dayString = '六'; break;
              }
              let week = `星期${dayString}`;
              let date = `(${obj.year}-${obj.month + 1}-${obj.date})`;
              // 挂号分上午和下午
              obj['text'] = `${week} 上午 ${date}`;
              obj2['text'] = `${week} 下午 ${date}`;
              texts.push(obj['text']);
              texts.push(obj2['text']);
              dateList.push(obj);
              dateList.push(obj2);
            }
            this.cache.dates = dateList;

            this.listData = texts;
            this.appBarTitle = constant.select_date;
            this.btnNext = constant.finish;
            break;
        }
      },
      selectedIndex(value) {
        this.indexes[this.step] = value;
      }
    },
    methods: {
      onItemClick(index) {
        this.selectedIndex = index;
      },
      onBtnPreviousClick() {
        this.step--;
        this.selectedIndex = this.indexes[this.step];
      },
      onBtnNextClick() {
        if (this.step === 6) {
          this.dialog.address = constant.provinces[this.indexes[0]] +
              constant.districts[this.indexes[0]][this.indexes[1]] +
              constant.districts[this.indexes[1]][this.indexes[2]];
          this.dialog.hospital = this.cache.hospitals[this.indexes[3]].name;
          this.dialog.department = constant.departments[this.indexes[4]];
          if (this.indexes[5] < 0) {
            this.dialog.doctor = '';
          } else {
            this.dialog.doctor = constant.doctors[this.indexes[5]];
          }
          this.dialog.date = this.cache.dates[this.indexes[6]].text;

          this.openDialog = true;
          return;
        }

        this.step++;

        if (this.selectedIndex !== this.indexes[this.step - 1]) {
          for (let i = this.step; i < this.indexes.length; i++) {
            this.indexes[i] = -1;
          }
        }

        this.selectedIndex = this.indexes[this.step];

        // 前 3 个步骤使用的是静态的省市县（区）数据，会在列表中一次加载完全，所有没有“加载更多”的操作
        this.loadedAll = this.step < 3;
      },
      onDialogCancel() {
        this.openDialog = false;
      },
      onDialogConfirm() {
        this.openDialog = false;

        let date = this.cache.dates[this.indexes[constant.nameSteps.datetime]];
        let month = date.month < 9 ? '0' + (date.month + 1) : (date.month + 1);
        let d = date.date < 10 ? '0' + date.date : date.date;
        let dateString = `${date.year}-${month}-${d}`;

        AppointmentService.doAppointment(this.cache.hospitals[this.indexes[constant.nameSteps.hospital]].id,
            constant.departments[this.indexes[constant.nameSteps.department]],
            constant.doctors[this.indexes[constant.nameSteps.doctor]], dateString)
            .then(res => {
              if (res.code === SUCCESS) {
                this.$toast.info('挂号成功');
                setTimeout(() => {
                  this.$router.push({name: 'Homepage'});
                }, 300);
              } else {
                this.$toast.info(res.message);
              }
            })
            .catch(e => {
              console.log(e);
              this.$toast.info(constant.network_error);
            });
      },
      load() {
        switch (this.step) {
          case 4:
            this.loading = true;

            HospitalService.searchHospital(
                constant.provinces[this.indexes[0]],
                constant.districts[this.indexes[0]][this.indexes[1]],
                constant.districts[this.indexes[1]][this.indexes[2]],
                ++this.page)
                .then(res => {
                  if (res.code === SUCCESS) {
                    res.value.value.forEach(it => {
                      this.listData.push(it.name);
                      // 将医院列表缓存起来
                      this.cache.hospitals.push(it);
                    });

                    if (res.value.currentPage >= res.value.maxPage) {
                      // 所有医院已全部加载
                      this.loadedAll = true;
                    }
                  } else {
                    this.$toast.info(res.message);
                  }

                  this.loading = false;
                })
                .catch(e => {
                  console.log(e);
                  this.$toast.info(constant.network_error);
                });

            break;
        }
      },

    }
  }
</script>

<style scoped>
  #root {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    position: absolute;
  }

  .mu-appbar {
    width: 100%;
  }

  .nav-wrapper {
    bottom: 0;
    width: 100%;
    border-radius: 0;
    max-width: 100%;
  }

  .nav-wrapper .nav {
    padding: 8px 0;
  }

  #btn-next {
    margin-left: 8px;
  }

  #list-wrapper {
    flex: 1;
    overflow: auto;
  }

  .dialog-text-label {
    font-size: 14px;
    line-height: 28px;
    font-weight: 400;
    margin: 0;
    padding: 0;
    color: rgba(0, 0, 0, .54);;
    box-sizing: border-box;
  }

  .dialog-text {
    font-size: 16px;
    line-height: 24px;
    padding: 4px 0;
    color: rgba(0, 0, 0, .87);
    font-weight: 400;
    margin: 0;
    box-sizing: border-box;
  }

  .dialog-text-wrap {
    margin-bottom: 8px;
  }
</style>